package com.qiu.greened.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.qiu.greened.bean.PostBean
import com.qiu.greened.network.PostService
import com.qiu.greened.utils.MyData

/**
 * 定义分页数据的数据源,以及从该数据源获取数据的方式
 */
class PostHotPagingSource(private val postService: PostService) : PagingSource<Int, PostBean>() {
    override fun getRefreshKey(state: PagingState<Int, PostBean>): Int? {
//        return state.anchorPosition
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PostBean> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
//            "${MyData.login}".showToast()
            val postList = postService.getPostHot(MyData.token, MyData.userId, page, pageSize).dataConvert()
            val prevKey = if (page > 1) page - 1 else null
            val nextKey = if (postList.isNotEmpty()) page + 1 else null
            LoadResult.Page(postList, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}